//
//  SGImgDetailVC.m
//  HomePurchase
//
//  Created by Rowling on 2020/3/19.
//  Copyright © 2020 蜀归科技. All rights reserved.
//

#import "ZMImageDetailVC.h"
#import <Photos/Photos.h>

@interface ZMImageDetailVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UILabel  *titleLab;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleTop;
@property (assign, nonatomic) NSInteger  index;

@end

@implementation ZMImageDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.hbd_barHidden = YES;
//    [self setLeftButtonImage:[UIImage new]];
    self.view.backgroundColor = UIColor.blackColor;
    _imgArr = [NSMutableArray arrayWithArray:_imgArr];
    _titleTop.constant = SG_STATUS_HEIGHT;
    if (_titles.length == 0) {
        _titleLab.text = [NSString stringWithFormat:@"1/%ld", _imgArr.count];
    }else{
        _titleLab.text = _titles;
    }
    switch (_type) {
        case DeleteImg:   [_rightBtn setImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateNormal]; break;
        case DownloadImg: [_rightBtn setImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal]; break;
        default: _rightBtn.hidden = YES; break;
    }
    self.imgCollection.bounces = NO;
    [self.imgCollection registerClass:[ZMImageDetailCell class] forCellWithReuseIdentifier:@"ZMImageDetailCell"];
    [self.imgCollection reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imgArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZMImageDetailCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZMImageDetailCell" forIndexPath:indexPath];
    return cell;
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    ZMImageDetailCell *reCell = (ZMImageDetailCell *)cell;
    UIImage *img;
    if([_imgArr[indexPath.row] isKindOfClass:[UIImage class]]){
        // UIImage
        img = _imgArr[indexPath.row];
    }else if([_imgArr[indexPath.row] containsString:@"http"]){
        //网络图片
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_imgArr[indexPath.row]]];
        img = [UIImage imageWithData:data];
    }else{
        img = [UIImage imageNamed:_imgArr[indexPath.row]];
    }
    reCell.image = img;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SG_SCREEN_WIDTH, SG_SCREEN_HEIGHT - SG_STATUS_HEIGHT - 44);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGFloat contentX = _imgCollection.contentOffset.x;
    _titleLab.text = [NSString stringWithFormat:@"%ld/%ld", (long)(contentX / SG_SCREEN_WIDTH) + 1, _imgArr.count];
}

#pragma mark - Button Action
- (IBAction)backClick:(id)sender {
    if (_dismiss) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)rightClick:(UIButton *)sender {
    if (_type == DeleteImg) {
        //删除
        if (_imgArr.count == 1) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [_imgArr removeObjectAtIndex:_index];
            [_imgCollection reloadData];
            _titleLab.text = [NSString stringWithFormat:@"1/%ld", _imgArr.count];
        }
        if (self.rightClickBlock) {
            self.rightClickBlock(_index);
        }
    }else{
        //下载
        ZMImageDetailCell *cell = (ZMImageDetailCell *)[_imgCollection cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_index inSection:0]];
        UIImageWriteToSavedPhotosAlbum(cell.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if(error){
        [SGDialog showWeakStr:@"保存失败" withImg:@""];
    }else{
        [SGDialog showWeakStr:@"保存成功" withImg:@""];
    }
}

@end


@interface ZMImageDetailCell () <UIScrollViewDelegate>
@property(nonatomic,weak) UIScrollView *scrollView;
@property(nonatomic,weak) UIImageView  *imageView;
@end

@implementation ZMImageDetailCell
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self configSubViews];
    }
    return self;
}


- (void)configSubViews{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SG_SCREEN_WIDTH, self.contentView.frame.size.height)];
    scrollView.delegate = self;
    scrollView.maximumZoomScale = 3.0;//最大缩放倍数
    scrollView.minimumZoomScale = 1.0;//最小缩放倍数
    scrollView.showsVerticalScrollIndicator   = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.backgroundColor = [UIColor blackColor];
    [self addSubview:scrollView];
    self.scrollView = scrollView;
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.userInteractionEnabled  = YES;//在UIImageView上加手势识别，打开用户交互
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    [doubleTap setNumberOfTapsRequired:2];
    [imageView addGestureRecognizer:doubleTap];//添加双击手势
    [scrollView addSubview:imageView];
    self.imageView = imageView;
}

- (void)setImage:(UIImage *)image{
    _image = image;
    self.imageView.image = image;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    CGFloat maxHeight = self.scrollView.bounds.size.height;
    CGFloat maxWidth = self.scrollView.bounds.size.width;
    //如果图片尺寸大于view尺寸，按比例缩放
    if(width > maxWidth || height > width){
        CGFloat ratio = height / width;
        CGFloat maxRatio = maxHeight / maxWidth;
        if(ratio < maxRatio){
            width = maxWidth;
            height = width*ratio;
        }else{
            height = maxHeight;
            width = height / ratio;
        }
    }
    self.scrollView.contentSize = CGSizeMake(width, height);
    [self.scrollView setZoomScale:1.f];
    self.imageView.frame = CGRectMake((maxWidth - width) / 2, (maxHeight - height) / 2, width, height);
    [self.scrollView layoutIfNeeded];
}

#pragma mark UIScrollViewDelegate
//指定缩放UIScrolleView时，缩放UIImageView来适配
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

//缩放后让图片显示到屏幕中间
- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    CGSize originalSize = _scrollView.bounds.size;
    CGSize contentSize = _scrollView.contentSize;
    CGFloat offsetX = originalSize.width > contentSize.width ? (originalSize.width - contentSize.width) / 2 : 0;
    CGFloat offsetY = originalSize.height > contentSize.height ? (originalSize.height - contentSize.height) / 2 : 0;
    self.imageView.center = CGPointMake(contentSize.width / 2 + offsetX, contentSize.height / 2 + offsetY);
    [self setNeedsLayout];
}

- (void)handleDoubleTap:(UITapGestureRecognizer *)recongnizer{
    UIGestureRecognizerState state = recongnizer.state;
    switch (state) {
        case UIGestureRecognizerStateBegan:
            break;
        case UIGestureRecognizerStateChanged:
            break;
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:{
            //以点击点为中心，放大图片
            CGPoint touchPoint = [recongnizer locationInView:recongnizer.view];
            BOOL zoomOut = self.scrollView.zoomScale == self.scrollView.minimumZoomScale;
            CGFloat scale = zoomOut?self.scrollView.maximumZoomScale:self.scrollView.minimumZoomScale;
            [UIView animateWithDuration:0.3 animations:^{
                self.scrollView.zoomScale = scale;
                if(zoomOut){
                    CGFloat x = touchPoint.x*scale - self.scrollView.bounds.size.width / 2;
                    CGFloat maxX = self.scrollView.contentSize.width-self.scrollView.bounds.size.width;
                    CGFloat minX = 0;
                    x = x > maxX ? maxX : x;
                    x = x < minX ? minX : x;
                    
                    CGFloat y = touchPoint.y * scale-self.scrollView.bounds.size.height / 2;
                    CGFloat maxY = self.scrollView.contentSize.height-self.scrollView.bounds.size.height;
                    CGFloat minY = 0;
                    y = y > maxY ? maxY : y;
                    y = y < minY ? minY : y;
                    self.scrollView.contentOffset = CGPointMake(x, y);
                }
            }];
        }
            break;
        default:break;
    }
}



@end
